<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/7
 * Time: 13:48
 */

namespace app\admin\controller;

use app\admin\model\GoldEggLog;
use app\admin\model\Message;
use app\admin\model\User as UserModel;
use app\admin\model\User;
use app\admin\model\WinterRecord;
use think\cache\driver\Redis;
use think\Db;

class Activity extends Index
{
    /**
     * @return \think\response\View
     * @user 帅吴
     * @date 2018/12/7
     * @time 13：40
     * @title 双十二集勋章兑换礼物记录表
     */
    public function honorIndex()
    {
        return view();
    }

    /**
     * @return \think\response\View
     * @user 帅吴
     * @date 2018/12/7
     * @time 13：40
     * @title 双十二集勋章兑换礼物记录表数据
     */
    public function honorIndexData()
    {

        $page_config = array(
            'page' => input('get.offset',1),
            'list_rows' => input('get.limit',10)
        );

        $where = [];
        if(!empty(input('key')) && !empty(input('value'))){

            $key = input('key');$value = input('value');
            if($key == 'nickname'){
                $where[] = [$key,'like','%'.$value.'%'];
            }
            $where[] = [$key,'=',$value];
        }



        $order = input('sort', 'id') . ' ' . input('order', 'asc');

        $redis = new \Redis();
        $redis->connect(config('app.redis.host'), 6379);
        $redis->auth(config('app.redis.pwd'));
//        $userIds = \app\admin\model\User::field('id,nickname,u_id')->where($where)->order($order)->paginate($page_config);
        $userIds = \app\admin\model\User::field('user_id as id,nickname,u_number as u_id')->where($where)->order($order)->paginate($page_config);

        $data = [];
        foreach($userIds as $key => $value){

            $k = 'user_stock'.$userIds[$key]['id'];
            $kk = 'HonorSum'.$userIds[$key]['id'];
            $gift_id = $redis->get($k);
            $honorSum = $redis->get($kk);

            if($gift_id){
                $userIds[$key]['gift_id'] = $gift_id;
                $userIds[$key]['honor_sum'] = $honorSum;
                $userIds[$key]['gift_name'] = \app\admin\model\Gift::where('id','=',$gift_id)->value('gift_name');
            }
        }
        return json($userIds);
    }

    public function activityRank()
    {
        $userIds = \app\admin\model\User::field('id,nickname,u_id')->select();

        $redis = new \Redis();
        $redis->connect(config('app.redis.host'), 6379);
        $redis->auth(config('app.redis.pwd'));
        $data = [];
        foreach($userIds as $key => $value){

            $k = 'user_stock'.$userIds[$key]['id'];
            $kk = 'HonorSum'.$userIds[$key]['id'];
            $kkk = 'current_day_send'.$userIds[$key]['id'];
            $gift_id = $redis->get($k);
            $honorSum = $redis->get($kk);
            $three = $redis->get($kkk);

            if(empty($honorSum)){
                continue;
            }
            if($honorSum){
                $data[$key]['u_id'] = $value['u_id'];
                $data[$key]['nickname'] = $value['nickname'];
                $data[$key]['honor_sum'] = $honorSum;
                $data[$key]['three'] = $three?'是':'否';
               $data[$key]['gift_name'] = \app\admin\model\Gift::where('id','=',$gift_id)->value('gift_name');
            }
        }

      $honor_sum = array_column($data,'honor_sum');
        array_multisort($honor_sum,SORT_DESC,$data);
        return view()->assign('data',$data);
    }

    public function activityExport()
    {
        $userIds = \app\admin\model\User::field('id,nickname,u_id')->select();

        $redis = new \Redis();
        $redis->connect(config('app.redis.host'), 6379);
        $redis->auth(config('app.redis.pwd'));
        $data = [];
        foreach($userIds as $key => $value){
            $k = 'user_stock'.$userIds[$key]['id'];
            $kk = 'HonorSum'.$userIds[$key]['id'];
            $kkk = 'current_day_send'.$userIds[$key]['id'];
            $gift_id = $redis->get($k);
            $honorSum = $redis->get($kk);
            $three = $redis->get($kkk);
            if(empty($honorSum)){
                continue;
            }
            if($honorSum){
                $result['u_id'] = $value['u_id']?$value['u_id']:'无';
                $result['nickname'] = $value['nickname']?$value['nickname']:'无';
                $result['honor_sum'] = $honorSum?$honorSum:0;
                $result['three'] = $three?'是':'否';
                $result['gift_name'] = \app\admin\model\Gift::where('id','=',$gift_id)->value('gift_name');
                if(empty($result['gift_name'])) $result['gift_name'] = '无';
                $data[] = $result;
            }
        }
       // $data = json_encode($data);
        $fileName = '勋章礼袋详情';
        $remarkData = ['勋章礼袋'];
        $cellTitle = [
            ['u_id','用户id'],
            ['nickname','用户昵称'],
            ['honor_sum','勋章数量'],
            ['three','日消费是否满300钻'],
            ['gift_name','奖品名称'],
        ];
        $excelObj = new \app\common\api\Excel();
        $excelObj->exportExcel($fileName,$remarkData,$cellTitle,$data);
    }

    /**
     * @return \think\response\View
     * @title 指定房间流水
     */
    public function especialRoom()
    {
        return view();
    }

    public function especialRoomData()
    {
        $userModel = new UserModel();
        $roomModel = new \app\admin\model\Room();
        $redis = new \Redis();
        $redis->connect(config('app.redis.host'), 6379);
        $redis->auth(config('app.redis.pwd'));
       $ids =  json_decode($redis->get('especialRoom'),true);
       $room_ids = [];
       foreach($ids as $key=>$value){
           $room_id = $roomModel->where(['r_id'=>$value])->value('id');
           array_push($room_ids,$room_id);
       }
       $map[] = ['id','in',$room_ids];
        $page_config = array(
            'page' => input('offset', 1),
            'list_rows' => input('limit',10),
        );
        $data = $roomModel->where($map)->field('r_name,r_id')->paginate($page_config);
        foreach($data as $key=>$value){
            $data[$key]['u_id'] = $userModel->where(['id'=>$value['r_id']])->value('u_id');
        }
        return json($data);
    }
    public function especialRoomAdd()
    {
        $redis = new \Redis();
        $redis->connect(config('app.redis.host'), 6379);
        $redis->auth(config('app.redis.pwd'));
        $ids =  json_decode($redis->get('especialRoom'),true);

        $u_id = input('u_id');

        $id = User::where('u_id','eq',$u_id)->value('id');

        if(in_array($id,$ids)) $this->error('房间已存在');
        if(!empty($id)){
            array_push($ids,$id);
           $res = $redis->set('especialRoom',json_encode($ids));
           if($res) $this->success('添加成功');
           else $this->error('添加失败');

        }else $this->error('未输入UID');
    }

    public function especialRoomDel()
    {
        $u_id = input('u_id');
        $id = User::where('u_id','=',$u_id)->value('id');
        $redis = new \Redis();
        $redis->connect(config('app.redis.host'), 6379);
        $redis->auth(config('app.redis.pwd'));
        $ids =  json_decode($redis->get('especialRoom'),true);

        foreach($ids as $key=>$value){
            if($value == $id){
                unset($ids[$key]);
                break;
            }
        }
        $res = $redis->set('especialRoom',json_encode($ids));
        if($res) return ['code'=>100,'msg'=>'删除成功'];
        else return ['code'=>-100,'msg'=>'删除失败'];

    }

    public function setPigCard()
    {
        return view();
    }

    public function setPigCardData()
    {
        $userModel = new UserModel();
        $data = $userModel->setPigCardData();
        return json($data);
    }

    public function setPigCardAdd()
    {
        $userModel = new UserModel();
        $res = $userModel->setPigCardAdd();
        if($res['code']==100) $this->success($res['msg']);
        else $this->error($res['msg']);
    }

    //抽奖数据
    public function drawData()
    {
        if(input('get.')){

            $start_time = strtotime(input('start_time'));
            $end_time = strtotime(input('end_time'));
            $u_id = input('u_id');
            $mode_type = input('mode_type');

            if($u_id) $user_id = User::where('u_id',$u_id)->value('id');


            if(!$start_time || !$end_time) return ['code'=>-100,'msg'=>'时间不能为空'];

            if($u_id && !$mode_type){
                $map[] = ['gold_egg_id','eq',18];
                $map[] = ['user_id','eq',$user_id];
                $map[] = ['add_time','between',[$start_time,$end_time] ];

                $goldEggLog = new GoldEggLog();
                $one_consume =  $goldEggLog->where($map)->count();
                $map[0] = ['gold_egg_id','eq',19];
                $two_consume = $goldEggLog->where($map)->count();
                $one_consume = $one_consume * 20;
                $two_consume = $two_consume * 200;

                $map1[] = ['a.gold_egg_id','eq',18];
                $map1[] = ['a.user_id','eq',$user_id];
                $map1[] = ['a.add_time','between',[$start_time,$end_time] ];
                $one_profit = $goldEggLog->alias('a')->join('gift_url b','a.gift_id = b.id','left')->where($map1)->sum('b.diamonds');
                $map1[0] = ['a.gold_egg_id','eq',19];
                $two_profit = $goldEggLog->alias('a')->join('gift_url b','a.gift_id = b.id','left')->where($map1)->sum('b.diamonds');

            }elseif ($u_id && $mode_type){
                $map[] = ['gold_egg_id','eq',18];
                $map[] = ['user_id','eq',$user_id];
                $map[] = ['mode_type','eq',$mode_type];
                $map[] = ['add_time','between',[$start_time,$end_time] ];
                $goldEggLog = new GoldEggLog();
                $one_consume =  $goldEggLog->where($map)->count();
                $map[0] = ['gold_egg_id','eq',19];
                $two_consume = $goldEggLog->where($map)->count();
                $one_consume = $one_consume * 20;
                $two_consume = $two_consume * 200;

                $map1[] = ['a.gold_egg_id','eq',18];
                $map1[] = ['a.user_id','eq',$user_id];
                $map1[] = ['a.mode_type','eq',$mode_type];
                $map1[] = ['a.add_time','between',[$start_time,$end_time] ];

                $one_profit = $goldEggLog->alias('a')->join('gift_url b','a.gift_id = b.id','left')->where($map1)->sum('b.diamonds');
                $map1[0] = ['a.gold_egg_id','eq',19];
                $two_profit = $goldEggLog->alias('a')->join('gift_url b','a.gift_id = b.id','left')->where($map1)->sum('b.diamonds');

            }elseif ($mode_type){
                $map[] = ['gold_egg_id','eq',18];
                $map[] = ['mode_type','eq',$mode_type];
                $map[] = ['add_time','between',[$start_time,$end_time] ];
                $goldEggLog = new GoldEggLog();
                $one_consume =  $goldEggLog->where($map)->count();
                $map[0] = ['gold_egg_id','eq',19];
                $two_consume = $goldEggLog->where($map)->count();
                $one_consume = $one_consume * 20;
                $two_consume = $two_consume * 200;

                $map1[] = ['a.gold_egg_id','eq',18];
                $map1[] = ['a.mode_type','eq',$mode_type];
                $map1[] = ['a.add_time','between',[$start_time,$end_time] ];
                $one_profit = $goldEggLog->alias('a')->join('gift_url b','a.gift_id = b.id','left')->where($map1)->sum('b.diamonds');
                $map1[0] = ['a.gold_egg_id','eq',19];
                $two_profit = $goldEggLog->alias('a')->join('gift_url b','a.gift_id = b.id','left')->where($map1)->sum('b.diamonds');

            }else{

                $goldEggLog = new GoldEggLog();
                $map[] = ['gold_egg_id','eq',18];
                $map[] = ['add_time','between',[$start_time,$end_time] ];
                $one_consume =  $goldEggLog->where($map)->count();
                $map[0] = ['gold_egg_id','eq',19];
                $two_consume = $goldEggLog->where($map)->count();
                $one_consume = $one_consume * 20;
                $two_consume = $two_consume * 200;

                $map1[] = ['a.gold_egg_id','eq',18];
                $map1[] = ['a.add_time','between',[$start_time,$end_time] ];
                $one_profit = $goldEggLog->alias('a')->join('gift_url b','a.gift_id = b.id','left')->where($map1)->sum('b.diamonds');
                $map1[0] = ['a.gold_egg_id','eq',19];
                $two_profit = $goldEggLog->alias('a')->join('gift_url b','a.gift_id = b.id','left')->where($map1)->sum('b.diamonds');


            }

            $data = [
                'one_consume' => $one_consume,
                'two_consume' => $two_consume,
                'one_profit' => $one_profit,
                'two_profit' => $two_profit,
                'total_consume' => $one_consume + $two_consume,
                'total_profit' => $one_profit + $two_profit,
            ];
            return ['code'=>100,'data'=>$data];
        }
        return view()
            ;
    }


    //记录
    public function greenWinterRecord()
    {
        return view();
    }

    public function greenWinterRecordData()
    {
        $page_config = array(
            'page' => input('offset', 1),
            'list_rows' => input('limit',10),
        );
        $winterRecordModel = new WinterRecord();
        $data = $winterRecordModel
            ->alias('a')
            ->field('a.*,b.u_id,b.nickname')
            ->join('users b','a.user_id = b.id','left')
            // ->order('a.status DESC')
            ->order(['a.status'=>'DESC','a.create_time'=>'DESC'])
            ->paginate($page_config);
        foreach($data as $key => $value){
            $data[$key]['nickname'] = preg_replace_callback('/@E(.{6}==)/', function ($r) {
                return base64_decode($r[1]);
            }, $value['nickname']);
        }
        return json($data);
    }

    //审批
    public function greenWinterAgree()
    {
        $id = input('id');
        $winterRecordModel = new WinterRecord();
        $res = $winterRecordModel->where(['id'=>$id])->find();
        if($res['status'] == 1 ) return ['code'=>-100,'msg'=>'已批准'];

        Db::connect('db_data')->startTrans();
        try{
            User::where(['id'=>$res['user_id']])->setInc('diamonds',$res['diamonds']);
            $newData['update_time'] = time();
            $newData['operate'] = session('admin_name');
            $newData['status'] = 1;
            $winterRecordModel->save($newData,['id'=>$id]);
            $info = [
                "user_id" => $res['user_id'],
                'title' => "暖冬活动",
                'content' => "您于【".date("Y-m-d H:i:s", time())."】领取的【".$res['bag_name'].'X'.$res['draw_num']."】礼包已发放，获得球币【".$res['diamonds']."】，请注意查收!",
                'have_read' => 1,
                'type' => 2,
                'status' => 1,
                'create_time' => time(),
            ];
            Message::create($info);
            Db::connect('db_data')->commit();
            return ['code'=>100,'msg'=>'成功'];
        }catch (\Exception $e){
            Db::connect('db_data')->rollback();
            return ['code'=>-100,'msg'=>'失败'];
        }
    }
}